#include "editnoticedlg.h"
#include "ui_editnoticedlg.h"

EditNoticeDlg::EditNoticeDlg(qlonglong id,QList<DictData> sys_notice_status,QList<DictData> sys_notice_type,QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::EditNoticeDlg)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/image/res/stm.jpg"));

    this->sys_notice_status = sys_notice_status;
    this->sys_notice_type = sys_notice_type;
    this->id = id;
    if(id > 0){
        setWindowTitle("编辑公告");
        notice.noticeId = id;
    }
    init();
}

EditNoticeDlg::~EditNoticeDlg()
{
    delete ui;
}

void EditNoticeDlg::on_btn_cancel_clicked()
{
    close();
}

void EditNoticeDlg::init()
{
    ui->comboBox_notiveType->addItem("");
    for (int i = 0; i < sys_notice_type.size(); ++i) {
        ui->comboBox_notiveType->addItem(sys_notice_type.at(i).dictLabel,sys_notice_type.at(i).dictValue);
    }
    if(id > 0){
        NoticeManagerApi api;
        QByteArray *data = api.getById(id);
        QJsonObject obj = QJsonDocument::fromJson(*data).object();
        if(obj.value("code").toInt() != 200){
            QMessageBox::warning(0,"提示",obj.value("msg").toString());
        }
        notice = Notice::toNotice(obj.value("data").toObject());
        ui->lineEdit_noticeTitle->setText(notice.noticeTitle);
        for (int i = 0; i < ui->comboBox_notiveType->count(); ++i) {
            if(ui->comboBox_notiveType->itemData(i).value<QString>() == notice.noticeType){
                ui->comboBox_notiveType->setCurrentIndex(i);
            }
        }
        notice.status == "0" ? ui->radioButton_normal->setChecked(1) : ui->radioButton_close->setChecked(1);
        ui->textEdit->setPlainText(notice.noticeContent);
    }
}


void EditNoticeDlg::on_btn_ok_clicked()
{
    if(ui->lineEdit_noticeTitle->text().isEmpty()){
        ui->lineEdit_noticeTitle->setStyleSheet("border-radius:10px;border:1px solid red;");
        return;
    }else{
        ui->lineEdit_noticeTitle->setStyleSheet("border-radius:10px;");
    }
    if(ui->comboBox_notiveType->currentData().isNull()){
        ui->comboBox_notiveType->setStyleSheet("border-radius:10px;border:1px solid red;");
        return;
    }else{
        ui->comboBox_notiveType->setStyleSheet("border-radius:10px;");
    }
    notice.noticeTitle = ui->lineEdit_noticeTitle->text();
    notice.noticeType = ui->comboBox_notiveType->currentData().value<QString>();
    notice.noticeContent = ui->textEdit->toPlainText();
    notice.status = ui->radioButton_normal->isChecked() ? "0" : "1";
    NoticeManagerApi api;
    QByteArray *data = api.editNotice(id,notice);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    if(obj.value("code").toInt() == 200){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        emit success();
        close();
    }
}

